package cn.szzsi.business.apiservice;


import cn.szzsi.common.util.CommonUtil;
import cn.szzsi.aci.dto.StoreDto;
import cn.szzsi.model.BrandStore;
import cn.szzsi.model.Member;
import cn.szzsi.aci.service.StoreInterface;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.json.FastJson;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import org.apache.commons.codec.digest.DigestUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by admin on 2017/6/2.
 */
public class StoreService  implements StoreInterface {


    //获取门店列表
    @Override
    public List<StoreDto> getStoreList(String shopId, String province, String city, String district) {
        Long start=System.currentTimeMillis();
        if(Member.dao.findById(shopId)==null){
            return null;
        }

        String sql="select * from sys_brand_store where 1=1 and type=0";
        sql+=" and shopId='"+shopId+"'";

        if(StrKit.notBlank(province)&& !"请选择".equals(province)&& !"全部".equals(province)){
            sql +=" and province='"+province+"'";
        }

        if(StrKit.notBlank(city)&&!"请选择".equals(city)&& !"全部".equals(city)){
            sql +=" and city='"+city+"'";
        }

        if(StrKit.notBlank(district)&&!"请选择".equals(district)&&!"市辖区".equals(district)&& !"全部".equals(district)){
            sql +=" and district='"+district+"'";
        }
        List<BrandStore>list=BrandStore.dao.find(sql);
        List<StoreDto> StoreDtoList=new ArrayList();

        for(BrandStore bs:list){
            FastJson fastJson=new FastJson();
            StoreDto storeDto=fastJson.parse(JsonKit.toJson(bs),StoreDto.class);
            StoreDtoList.add(storeDto);
        }
        Long end =System.currentTimeMillis();
        return StoreDtoList;
    }

    //获取门店详情
    @Override
    public StoreDto getStoreInfo(String shopId,String storeNum) {
        BrandStore bs=BrandStore.dao.getByStoreNumAndShopId(storeNum,shopId);
        FastJson fastJson=new FastJson();
        StoreDto storeDto=fastJson.parse(JsonKit.toJson(bs),StoreDto.class);
        if(bs==null){
            try {
                throw new Exception("门店不存在!");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }else{
           return storeDto;
        }
    }

    /**
     * 唤醒首页
     * @param shopId
     * @return
     */
    @Override
    public JSONObject getStoreInfo(String shopId) {
        List<BrandStore> brandStores=BrandStore.dao.find("select bs.province, bs.city,bs.longitude,bs.latitude,count(*) amount from sys_brand_store bs where shopId=? and city is not null group by city",shopId);
        List<BrandStore>cityBrandStores=BrandStore.dao.find("select id,province,city from sys_brand_store where shopId=? and city is not null",shopId);
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("count",cityBrandStores.size());
        JSONObject jsonCity=new JSONObject();
        for(int i=0;i<brandStores.size();i++){
            BrandStore brandStore=brandStores.get(i);
            String city=brandStore.getCity();
            if("市辖区".equals(city)||"市辖县".equals(city)){
                city=brandStore.getProvince();
            }

            JSONObject jsonCityValue=new JSONObject();
            JSONArray arrayGinwave=new JSONArray();
            arrayGinwave.add(brandStore.getLongitude());
            arrayGinwave.add(brandStore.getLatitude());
            jsonCityValue.put("ginwave",arrayGinwave);
            jsonCityValue.put("storeAmount",brandStore.get("amount"));

            JSONArray arrayId=new JSONArray();
            for(BrandStore cityBrandStore:cityBrandStores){
                if(city.equals(cityBrandStore.getCity())|| city.equals(cityBrandStore.getProvince())){
                    arrayId.add(cityBrandStore.getId());
                }
            }
            jsonCityValue.put("storeIds",arrayId);
            jsonCity.put(city,jsonCityValue);


        }
        jsonObject.put("city",jsonCity);
        return jsonObject;
    }

    /**
     * 根据传入的门店id获取对应的门店列表
     * @param storeIds
     * @return
     */
    @Override
    public List<StoreDto> getStoreInfos(String storeIds) {
        org.json.JSONArray jsonArray = new org.json.JSONArray(storeIds);
        List<StoreDto> StoreDtoList=new ArrayList();
        String ids="";
        for(int i=0;i<jsonArray.length();i++){
            ids+=JsonKit.toJson(jsonArray.getString(i))+",";

        }
        if(ids.endsWith(",")){
            ids= ids.substring(0,ids.length()-1);
        }
        String sql="select * from sys_brand_store where id in("+ids+")";
        List<BrandStore>brandStores=BrandStore.dao.find(sql);
        for(BrandStore brandStore:brandStores){
            FastJson fastJson=new FastJson();
            StoreDto storeDto=fastJson.parse(JsonKit.toJson(brandStore),StoreDto.class);
            StoreDtoList.add(storeDto);
        }
       return StoreDtoList;
    }

    /**
     * 根据门店id获取门店详情
     * @param storeId
     * @return
     */
    @Override
    public StoreDto getById(String storeId) {
        BrandStore brandStore=BrandStore.dao.findById(storeId);
        if(brandStore!=null){
            FastJson fastJson=new FastJson();
            StoreDto storeDto=fastJson.parse(JsonKit.toJson(brandStore),StoreDto.class);
            return storeDto;
        }else{
            return null;
        }

    }


    /**
     * 根据微信推送过来的PoiId获取门店信息
     * @param poiId
     * @return
     */
    @Override
    public StoreDto getByPoiId(String poiId) {
        BrandStore brandStore=BrandStore.dao.getByPoiId(poiId);
        if(brandStore!=null){
            FastJson fastJson=new FastJson();
            StoreDto storeDto=fastJson.parse(JsonKit.toJson(brandStore),StoreDto.class);
            return storeDto;
        }else{
            return null;
        }
    }

    //保存店员信息
    @Override
    public String saveClerk(String username,String password,String shopId,String memberId) {
        if(Member.dao.findById(shopId)==null){
            return "店铺ID不存在";
        }
        if(StrKit.isBlank(memberId)){
            if(Member.dao.getCustomerByUsernameAndShopId(username,shopId)!=null){
                return "用户名已存在";
            }
            Member member=new Member();
            String id=CommonUtil.getUUID();
            member.set("username", username);
            member.set("password", DigestUtils.md5Hex(password));
            member.set("email", "");
            member.set("shopId","0");
            member.set("roleId", "");
            member.set("safeQuestion", null);
            member.set("safeAnswer", null);
            //member.set("memberRank_id", MemberRank.dao.getDefaultMemberRank(shopId).getStr("id"));
            member.set("point", 0);
            member.set("deposit", new BigDecimal("0"));
            member.set("isAccountEnabled", true);
            member.set("isAccountLocked", false);
            member.set("loginFailureCount", 0);
            member.set("passwordRecoverKey", null);
            member.set("lockedDate", null);
            member.set("loginDate", new Date());
            member.set("id",id);
            member.set("createDate", new Date());
            member.set("b_shoprank",shopId);
            member.set("brandStoreId","");
            member.set("userimgurl","");
            member.save();
            return id;
        }else{
            Member member=Member.dao.findById(memberId);
            if(Member.dao.updateUsername(username,shopId,memberId)!=null){
                try {
                    throw new Exception("用户名已存在!");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }else{
                member.set("username",username).set("password",password).update();
                return memberId;
            }
        }
    }

    /**
     * 更新门店信息
     * @param storeDto
     */
    @Override
    public void updateStoreInfo(StoreDto storeDto) {
        FastJson fastJson=new FastJson();
        BrandStore brandStore1=fastJson.parse(JsonKit.toJson(storeDto),BrandStore.class);
        brandStore1.update();
    }
}
